from asyncio import Future
import asyncio

f = Future()
print(f"done? {f.done()}")
f.set_result(42)
print(f"done? {f.done()}")
print(f"result? {f.result()}")

# f = Future()
# print(f"result? {f.result()}") #不能在set_result之前调用result()

f = Future()
f.set_exception(Exception("hahah"))
print(f"result? {f.done()}")


def make_request() -> Future:
    future = Future()
    # task就是future和coroutine的组合 创建任务就是创建一个空的future 里面运行协程得到结果后设置future的结果或者异常
    asyncio.create_task(set_future_value(future)) 
    return future

async def set_future_value(future):
    await asyncio.sleep(1)
    future.set_result(42)

async def main():
    future = make_request()
    print(f"work done? {future.done()}")
    value = await future
    print(f"work done? {future.done()}")
    print(value)

asyncio.run(main=main())